from flask import Flask, render_template, request, jsonify, session, redirect, url_for
from datetime import datetime
from database import Database
import json

app = Flask(__name__)
app.secret_key = 'parking_system_secret_key_2024'
db = Database()

@app.route('/')
def index():
    config = db.get_config()
    occupied = db.get_occupied_spaces()
    remaining = config.total_spaces - occupied
    return render_template('index.html', 
                         remaining=remaining, 
                         total=config.total_spaces,
                         occupied=occupied)

@app.route('/admin')
def admin():
    if 'admin' not in session:
        return redirect(url_for('login'))
    
    config = db.get_config()
    today_records = db.get_today_records()
    today_income = db.get_today_income()
    
    return render_template('admin.html', 
                         config=config,
                         today_records=today_records,
                         today_income=today_income)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.json.get('username')
        password = request.json.get('password')
        
        if db.admin_login(username, password):
            session['admin'] = username
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'message': '用户名或密码错误'})
    
    return render_template('login.html')

@app.route('/logout')
def logout():
    session.pop('admin', None)
    return redirect(url_for('index'))

@app.route('/api/entry', methods=['POST'])
def api_entry():
    data = request.json
    license_plate = data.get('license_plate')
    vehicle_type = data.get('vehicle_type', '小型车')
    
    if not license_plate:
        return jsonify({'success': False, 'message': '请输入车牌号'})
    
    # 检查是否已在场内
    existing = db.get_parking_record(license_plate)
    if existing:
        return jsonify({'success': False, 'message': '该车辆已在停车场内'})
    
    # 检查车位是否已满
    config = db.get_config()
    occupied = db.get_occupied_spaces()
    if occupied >= config.total_spaces:
        return jsonify({'success': False, 'message': '停车场已满'})
    
    record = db.add_parking_record(license_plate, vehicle_type)
    return jsonify({
        'success': True,
        'entry_time': record.entry_time.strftime('%Y-%m-%d %H:%M:%S'),
        'remaining': config.total_spaces - db.get_occupied_spaces()
    })

@app.route('/api/exit', methods=['POST'])
def api_exit():
    data = request.json
    license_plate = data.get('license_plate')
    
    record = db.get_parking_record(license_plate)
    if not record:
        return jsonify({'success': False, 'message': '未找到该车辆的入场记录'})
    
    fee = db.calculate_fee(record.entry_time)
    return jsonify({
        'success': True,
        'entry_time': record.entry_time.strftime('%Y-%m-%d %H:%M:%S'),
        'exit_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'parking_hours': round((datetime.now() - record.entry_time).total_seconds() / 3600, 2),
        'fee': fee
    })

@app.route('/api/pay', methods=['POST'])
def api_pay():
    data = request.json
    license_plate = data.get('license_plate')
    
    record = db.pay_parking_fee(license_plate)
    if record:
        return jsonify({
            'success': True,
            'fee': record.parking_fee,
            'remaining': db.get_config().total_spaces - db.get_occupied_spaces()
        })
    return jsonify({'success': False, 'message': '支付失败'})

@app.route('/api/records')
def api_records():
    if 'admin' not in session:
        return jsonify({'success': False, 'message': '未登录'})
    
    records = db.get_all_records()
    return jsonify({
        'success': True,
        'records': [{
            'id': r.id,
            'license_plate': r.license_plate,
            'vehicle_type': r.vehicle_type,
            'entry_time': r.entry_time.strftime('%Y-%m-%d %H:%M:%S') if r.entry_time else '',
            'exit_time': r.exit_time.strftime('%Y-%m-%d %H:%M:%S') if r.exit_time else '',
            'parking_fee': r.parking_fee,
            'is_paid': r.is_paid
        } for r in records]
    })

@app.route('/api/config', methods=['GET', 'POST'])
def api_config():
    if 'admin' not in session:
        return jsonify({'success': False, 'message': '未登录'})
    
    if request.method == 'POST':
        data = request.json
        db.update_config(
            total_spaces=int(data.get('total_spaces', 100)),
            first_hour_fee=float(data.get('first_hour_fee', 5.0)),
            additional_hour_fee=float(data.get('additional_hour_fee', 2.0))
        )
        return jsonify({'success': True})
    
    config = db.get_config()
    return jsonify({
        'success': True,
        'config': {
            'total_spaces': config.total_spaces,
            'first_hour_fee': config.first_hour_fee,
            'additional_hour_fee': config.additional_hour_fee
        }
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
